const request = require('../../utils/request');
class Drives {
    /**
     * 会员卡
     * @api {GET}         /                设备列表
     * @apiName           /drives
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiParam          {Int}            page           页数
     * @apiParam          {Int}            limit          条数
     * @apiParam          {String}         [keywords]     关键字
     * @apiParam          {Int}            type=1         类型
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": [
            {
                "id": 2,
                "price": "99.00",
                "actualPrice": "99.00",
                "day": 90,
                "limit": 10,
                "desc": "三个月洗车卡",
                "status": true,
                "createdAt": "2019-06-03T10:50:47.000Z",
                "updatedAt": "2019-06-03T10:50:49.000Z"
            }
        ]
       }
     */
    async index(ctx) {
        const {
            model,
            request: {
                query: { page = 1, limit = 10, keywords = '', type = 1 }
            }
        } = ctx;
        let status = parseInt(type);
        let sql;
        let num;
        if (ctx.user.User.role.role === 'admin') {
            if (keywords.trim()) {
                // 关键字不为空
                if (status === 1) {
                    sql =
                        "SELECT `drives`.`id`,`drives`.`deviceId`,`drives`.`areaName`,`drives`.`isOnline`,`drives`.`useState`,`drives`.`src`,`drives`.`lng`,`drives`.`lat`,`admins`.`username`,`admins`.`phone` FROM`drives` AS `drives`INNER JOIN `admins` AS `admins` ON drives.merchantId = admins.id WHERE(`drives`.`deviceId` LIKE '%" +
                        keywords +
                        "%' OR `admins`.`username` LIKE '%" +
                        keywords +
                        "%'OR `admins`.`phone` LIKE '%" +
                        keywords +
                        "%') LIMIT " +
                        (page - 1) * 10 +
                        ',' +
                        limit;
                    num =
                        "SELECT `drives`.`id` FROM`drives` AS `drives`INNER JOIN `admins` AS `admins` ON drives.merchantId = admins.id WHERE(`drives`.`deviceId` LIKE '%" +
                        keywords +
                        "%' OR `admins`.`username` LIKE '%" +
                        keywords +
                        "%'OR `admins`.`phone` LIKE '%" +
                        keywords +
                        "%')";
                } else {
                    sql =
                        "SELECT `drives`.`id`,`drives`.`deviceId`,`drives`.`areaName`,`drives`.`isOnline`,`drives`.`useState`,`drives`.`src` FROM `drives`,`drives`.`lng`,`drives`.`lat` AS `drives`  WHERE merchantId = 0 AND `drives`.`deviceId` LIKE '%" +
                        keywords +
                        "%' LIMIT " +
                        (page - 1) * 10 +
                        ',' +
                        limit;
                    num =
                        "SELECT `drives`.`id` FROM`drives` AS `drives` WHERE merchantId = 0 AND `drives`.`deviceId` LIKE '%" +
                        keywords +
                        "%'";
                }
            } else {
                //关键字为空
                if (status === 1) {
                    sql =
                        'SELECT ' +
                        '`drives`.`id`,' +
                        '`drives`.`deviceId`,' +
                        '`drives`.`areaName`,' +
                        '`drives`.`isOnline`,' +
                        '`drives`.`useState`,' +
                        '`drives`.`lng`,' +
                        '`drives`.`lat`,' +
                        '`drives`.`src`,' +
                        '`admins`.`username`,' +
                        '`admins`.`phone` ' +
                        'FROM ' +
                        '`drives` AS `drives`' +
                        'INNER JOIN ' +
                        '`admins` AS `admins` ' +
                        'ON ' +
                        'drives.merchantId = admins.id ' +
                        'LIMIT ' +
                        (page - 1) * 10 +
                        ',' +
                        limit +
                        '';

                    num =
                        'SELECT `drives`.`id` ' +
                        'AS `count` ' +
                        'FROM ' +
                        '`drives` AS `drives`' +
                        'INNER JOIN ' +
                        '`admins` AS `admins` ' +
                        'ON ' +
                        'drives.merchantId = admins.id';
                } else {
                    sql =
                        'SELECT * FROM drives WHERE merchantId = 0 LIMIT ' +
                        (page - 1) * 10 +
                        ',' +
                        limit +
                        '';

                    num =
                        'SELECT `drives`.`id` AS `count` FROM `drives` WHERE merchantId = 0';
                }
            }

            let data = await model.query(sql);
            let count = await model.query(num);
            const res = { row: [], count: 0 };
            console.log(count[0].length);
            res.count = count[0].length;
            res.row = data[0];
            ctx.success(res);
        } else {
            if (keywords.trim()) {
                // 关键字不为空
                sql =
                    "SELECT `drives`.`id`,`drives`.`deviceId`,`drives`.`areaName`,`drives`.`isOnline`,`drives`.`useState`,`drives`.`src`,`drives`.`lng`,`drives`.`lat`,`admins`.`username`,`admins`.`phone` FROM`drives` AS `drives`INNER JOIN `admins` AS `admins` ON drives.merchantId = admins.id WHERE(`drives`.`deviceId` LIKE '%" +
                    keywords +
                    "%' OR `admins`.`username` LIKE '%" +
                    keywords +
                    "%'OR `admins`.`phone` LIKE '%" +
                    keywords +
                    "%') AND `drives`.`merchantId` = " +
                    ctx.user.User.id +
                    ' LIMIT ' +
                    (page - 1) * 10 +
                    ',' +
                    limit;
                num =
                    "SELECT `drives`.`id` FROM`drives` AS `drives`INNER JOIN `admins` AS `admins` ON drives.merchantId = admins.id WHERE(`drives`.`deviceId` LIKE '%" +
                    keywords +
                    "%' OR `admins`.`username` LIKE '%" +
                    keywords +
                    "%'OR `admins`.`phone` LIKE '%" +
                    keywords +
                    "%') AND `drives`.`merchantId` = " +
                    ctx.user.User.id;
            } else {
                //关键字为空
                sql =
                    'SELECT ' +
                    '`drives`.`id`,' +
                    '`drives`.`deviceId`,' +
                    '`drives`.`areaName`,' +
                    '`drives`.`isOnline`,' +
                    '`drives`.`useState`,' +
                    '`drives`.`lng`,' +
                    '`drives`.`lat`,' +
                    '`drives`.`src`,' +
                    '`admins`.`username`,' +
                    '`admins`.`phone` ' +
                    'FROM ' +
                    '`drives` AS `drives`' +
                    'INNER JOIN ' +
                    '`admins` AS `admins` ' +
                    'ON ' +
                    'drives.merchantId = admins.id WHERE `drives`.`merchantId` = ' +
                    ctx.user.User.id +
                    ' LIMIT ' +
                    (page - 1) * 10 +
                    ',' +
                    limit +
                    '';

                num =
                    'SELECT `drives`.`id` ' +
                    'AS `count` ' +
                    'FROM ' +
                    '`drives` AS `drives`' +
                    'INNER JOIN ' +
                    '`admins` AS `admins` ' +
                    'ON ' +
                    'drives.merchantId = admins.id WHERE `drives`.`merchantId` = ' +
                    ctx.user.User.id;
            }

            let data = await model.query(sql);
            let count = await model.query(num);
            const res = { row: [], count: 0 };
            console.log(count[0].length);
            res.count = count[0].length;
            res.row = data[0];
            ctx.success(res);
        }
    }
    /**
     * 设备分配
     * @api {PUT}         /:id              设备分配
     * @apiName           /drives
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiParam          {Number}       id           id
     * @apiParam          {Number}       merchantId   商户id
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
       }
     */
    async edit(ctx) {
        const {
            db,
            params: { id },
            request: {
                body: { merchantId }
            }
        } = ctx;

        if (ctx.user.User.role.role === 'admin') {
            let data = await db.Drives.findOne({ where: { id: id } });
            data.merchantId = merchantId;
            data.save();
            ctx.success();
        } else {
            ctx.errors('暂无权限');
        }
    }
    /**
     * 设备解绑
     * @api {POST}        /:id              设备解绑
     * @apiName           /drives
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
       }
     */
    async unbinding(ctx) {
        const {
            db,
            params: { id }
        } = ctx;
        let data = await db.Drives.findOne({ where: { id: id } });
        data.merchantId = 0;
        data.save();
        ctx.success();
    }
    /**
     * 设备删除
     * @api {DELETE}      /:id              设备删除
     * @apiName           /drives
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
       }
     */
    async deletes(ctx) {
        const {
            db,
            Op,
            params: { id }
        } = ctx;
        // 先查询是否有人绑定该设备
        let drives = await db.Drives.findOne({
            where: {
                id: id,
                merchantId: {
                    [Op.ne]: 0
                }
            }
        });
        if (drives) {
            ctx.errors('请先解绑设备');
            return;
        } else {
            db.Drives.destroy({ where: { id: id } });
            ctx.success();
        }
    }
    /**
     * 更新位置
     * @api {PUT}         /address/:id                更新位置
     * @apiName           /drives/address
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
       }
     */
    async address(ctx) {
        const {
            db,
            params: { id }
        } = ctx;
        let drives = await db.Drives.findOne({ where: { id: id } });
        let {
            result: { location }
        } = await request.post(
            {
                address: drives.areaName,
                key: 'VW5BZ-7YE6D-P7G4B-PN67H-O2ZY5-3NBFS'
            },
            'https://apis.map.qq.com/ws/geocoder/v1'
        );
        drives.lng = location.lng;
        drives.lat = location.lat;
        drives.save();
        ctx.success();
    }
    /**
     * 获取设备消费明细
     * @api {GET}         /detail                     获取设备消费明细
     * @apiName           /drives/detail
     * @apiGroup          Drives
     * @apiVersion 0.1.0
     * @apiParam          {String}         id         ID
     * @apiParam          {Int}            page       页数
     * @apiParam          {Int}            limit      条数
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            {
                "id": 2,
                "userId": 3,
                "merchantId": 7,
                "deviceId": 1,
                "address": "四川省成都市双流区麓山大道一段8号",
                "amount": "30.00",
                "payment": "会员抵扣",
                "status": true,
                "createdAt": "2019-06-04T07:48:38.000Z",
                "updatedAt": "2019-06-04T07:48:41.000Z"
            }
        }
      }
     */
    async detail(ctx) {
        const {
            db,
            Op,
            request: {
                query: { id, limit = 10, page = 1 }
            }
        } = ctx;

        let condition = {
            limit: parseInt(limit),
            offset: (parseInt(page) - 1) * 10,
            where: {
                deviceId: id,
                type: {
                    [Op.ne]: 1
                }
            }
        };

        let data = await db.Use.findAndCountAll(condition);
        ctx.success(data);
    }
}
module.exports = new Drives();
